$(document).ready(function () {
    setDioalog($("#data_dlg"));
    setDioalog($("#info_dialog"));
});

var base_url = "/data";
var doListUrl = "/toPage.do";
var vName = "", vCode = "", pvCode = "",
    fileName = "", vDesc = "",tips = "", allFields = "";

/*@returns {boolean}*/
function verifyInput(){
    var bValid = true;
     vName = $("#vName"),
         fileName = $("#file_name"),
         vCode = $("#vCode"),
        pvCode = $("#pvCode"),
        vDesc = $("#vDesc");
      tips = $("#validate_tips");
    allFields = $([]).add(vName).add(fileName).add(vCode).add(pvCode).add(name).add(vDesc);

    allFields.removeClass("ui-state-error");

    bValid = bValid && checkLength(vName, "版本名称", 1, 10);
    bValid = bValid && checkLength(fileName, "文件名称", 1, 10);
    bValid = bValid && checkLength(vCode, "版本号", 1, 10);
    bValid = bValid && checkLength(pvCode, "上一版本号", 0, 10);
    bValid = bValid && checkLength(vDesc, "版本描述", 0,100);

    bValid = bValid && checkRegexp(vName, new RegExp("^[ A-Za-z0-9\\u0391-\\uFFE5_]{" + 1 + "," +10 + "}$"),"请输入汉字、英文字母、数字、汉字标点及下划线");
    bValid = bValid && checkRegexp(fileName, new RegExp("^[ A-Za-z0-9\\u0391-\\uFFE5_]{" + 1 + "," +10 + "}$"), "请输入汉字、英文字母、数字、汉字标点及下划线");
    bValid = bValid && checkRegexp(vCode,   new RegExp("^[0-9]{" + 0 + "," +10 + "}$"), "请输入数字");
    bValid = bValid && checkRegexp(pvCode, new RegExp("^[0-9]{" + 0 + "," +10 + "}$"), "请输入数字");
    bValid = bValid && checkRegexp(vDesc, new RegExp("^[ A-Za-z0-9\\u0391-\\uFFE5_]{" + 0 + "," +100 + "}$"), "请输入汉字、英文字母、数字、汉字标点及下划线");

    return bValid;
}

/**
 * 搜索
 *
 * @param url
 */
function searchData()
{
    var jsonStr =
    {
        name:$('#name').val(),
        type:$('#type').val(),
        vCode:$('#code').val(),
        isSearch: true
    };
    doList(jsonStr, base_url + "/toPage.do", $("#data_list"));
}
/*dialog公用*/
function dataDialog(title,url,type){
    $("#data_dlg").dialog({
        dialogClass: "my-dialog",
        autoOpen: true,
        width: 850,
        modal: true,
        title: title,
        buttons: {
            "保存": function () {
                if (verifyInput())
                    store_data(url)
            },
            取消: function () {
                if(tips!="" || allFields!=""){
                    tips.text("").removeClass("ui-state-highlight");
                    allFields.removeClass( "ui-state-error").val("");
                }
                $(this).dialog('destroy');
                $(this).dialog("close");
                if(parseInt(type)==1){
                    $("#data_fm")[0].reset();
                }
            }
        },
        close: function() {
            tips.text("").removeClass("ui-state-highlight");
            allFields.removeClass( "ui-state-error").val("");
        }
    });
}
/**
 * 添加文件
 */
function create()
{
    var url = base_url + "/create.do";
    dataDialog("添加文件", url, 1);
    $(":input", "#data_fm").not(":button, :submit, :reset, :hidden").val("");
    $("#path_div").hide();
    $("#fileToUpload").val("");
}

/**
 * 保存
 *
 * @param url
 */
function store_data(url)
{
    $.ajax({
        cache: true,
        type: "POST",
        url: url,
        data: $('#data_fm').serialize(),
        async: false,
        error: function (request) {
            alert("网络连接失败！");
        },
        success: function (result) {
            var data = $.parseJSON(result);
            if (data.ok)
            {
                $("#data_dlg").dialog("close");
                window.location.reload(false);
            }
            else
            {
                $("#info_msg").css("text-align", "center").text(data.msg);
                $("#info_dialog").dialog({
                    dialogClass: "my-dialog",
                    autoOpen: true,
                    modal: true,
                    title: '提示信息',
                    buttons: {
                        "确定": function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
        }
    });
}

/**
 * 删除
 *
 * @param id
 */
function deleteData(id)
{
    if (0 != id && null != id)
    {
        $("#info_msg").css("text-align", "center").text("删除后将无法恢复，您确定要删除吗？");
        $("#info_dialog").dialog({
            dialogClass: "my-dialog",
            autoOpen: true,
            modal: true,
            title: '删除确认',
            buttons: {
                "确定": function () {
                    $.post("/data/deleteData.do?id=" + id, function (result) {
                        if (result.ok) {
                            $("#info_dialog").dialog("close");
                            window.location.reload(false);
                        }
                        else {
                            alert(result.msg);
                        }
                    }, 'json');
                },
                取消: function () {
                    $(this).dialog("close");
                }
            }
        });
    }
    else
        $("#info_msg").css("text-align", "center").text("您还没有选中任何文件，请选中后再删除！");
}

/**
 * 上传文件到临时目录（使用ajaxfileupload插件）
 */
function uploadFile()
{
    alert("上传中，请耐心等待！");
    var file = document.getElementById("fileToUpload").files[0];
    if (file != null)
    {
        var fileName = file.name;
        var suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length);
        $.ajaxFileUpload ({
            url : "/data/uploadFile.do",
            secureuri : false,
            fileElementId : "fileToUpload",
            dataType : "json",
            success : function (data, status){
                $("#info_msg").css("text-align", "center").text("上传文件成功！");
                $("#info_dialog").dialog({
                    dialogClass: "my-dialog",
                    autoOpen: true,
                    modal: true,
                    title: '提示信息',
                    buttons: {
                        确定: function () {
                            $(this).dialog("close");
                        }
                    }
                });
                $("#path").val(data.data);
                $("#suffix").val(suffix);
            },
            error: function (data, status, e){
                alert(e);
            }
        });
    }
}

/**
 * 修改文件信息
 *
 * @param id
 *
 * Added By Zmt
 */
function modifyData(id)
{
    $.post("/data/fetchData.do?id=" + id, function (result) {
        $("#data_dlg").html(result);
    });
    var url = "/data/modify.do?id=" + id;
    dataDialog("编辑文件", url, 2);
}

/**
 * 下载
 *
 * @param id
 */
function downloadData(id)
{
    window.location.href = "/data/download.do?id=" + id;
}